'use client';

import { Key } from 'react';
import { useState, useMemo } from 'react';

import { IllustrationNoContent } from '@/components/illustrations';
import { filterPublishedBlogs } from '@/utils/utils';

import { BlogListItem } from './blog-list-item';
import { Pagination } from './pagination';

import { type Blog } from '../types';

const ITEMS_PER_PAGE = 6;

export const BlogList = ({ blogs }: Blog) => {
    const [currentPage, setCurrentPage] = useState(1);

    // 过滤掉未来时间的博客
    const publishedBlogs = useMemo(() => {
        return filterPublishedBlogs(blogs);
    }, [blogs]);

    const { paginatedBlogs, totalPages } = useMemo(() => {
        const startIndex = (currentPage - 1) * ITEMS_PER_PAGE;
        const endIndex = startIndex + ITEMS_PER_PAGE;
        const paginatedBlogs = publishedBlogs.slice(startIndex, endIndex);
        const totalPages = Math.ceil(publishedBlogs.length / ITEMS_PER_PAGE);

        return { paginatedBlogs, totalPages };
    }, [publishedBlogs, currentPage]);

    const handlePageChange = (page: number) => {
        setCurrentPage(page);
        // 滚动到顶部
        window.scrollTo({ top: 0, behavior: 'smooth' });
    };

    if (!publishedBlogs.length) {
        return (
            <div className="grid place-content-center gap-8">
                <IllustrationNoContent className="size-[30vh]" />
                <h3 className="text-center text-2xl font-semibold tracking-tight">暂无Blog</h3>
            </div>
        );
    }

    return (
        <div>
            <ul className="grid grid-cols-1 gap-10 md:grid-cols-2 border-blue-700">
                {paginatedBlogs.map((el: { id: Key | null | undefined }, idx: number) => (
                    <BlogListItem blog={el} key={idx} />
                ))}
            </ul>

            <Pagination
                currentPage={currentPage}
                totalPages={totalPages}
                onPageChange={handlePageChange}
            />
        </div>
    );
};
